# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

# import logging
# _logger = logging.getLogger(__name__)

from odoo.addons.iot_mqtt.controllers.main import IotMqttInterface

from odoo import models, fields, api, _


class IotMqttModel(models.AbstractModel):
    controller = None
    _is_connect = None
    _name = "iot.mqtt.interface"
    _description = "Provides Mqtt functionalities to another models."

    # must set this field
    router_code = fields.Char(index=True)

    @api.model
    def action_mqtt(self):
        db = self.env.cr.dbname
        print('action_mqtt, IotMqttModel', db,  self._name)
        mycls = type(self)
        print('action_mqtt, IotMqttModel', mycls )
        if not self._is_connect:
            iot = IotMqttInterface(db, self._name)
            mycls.controller = iot
            mycls._is_connect = True
            self.subscribe()
            return True
        else:
            return False


    @api.model
    def publish(self, method, *args, **kwargs):
        print('gateway model, publish', method, args, kwargs)
        self.controller.publish( self.router_code, method,  *args, **kwargs)

    @api.model
    def subscribe(self ):
        self.controller.subscribe()

